package com.glela.common.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.glela.common.service.EmailService;
import com.zls.mail.BaseMail;
import com.zls.mail.FileMail;
import com.zls.mail.HtmlMail;
import com.zls.mail.TextMail;
import com.zls.rabbitmq.service.MailSenderService;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

@Service
public class EmailServiceImpl implements EmailService {
	private static final Logger	logger				= LoggerFactory.getLogger(EmailServiceImpl.class);
	/** 邮件模版根路径 */
	private static final String	MAIL_TEMPLATE_PATH	= "mail";

	@Autowired
	private MailSenderService		mailSenderService;
	@Resource(name = "freemarker")
	private FreeMarkerConfigurer	freemarker;
	private Configuration			configuration;

	@Override
	public boolean send(TextMail mail) {
		try {
			if (mail.checkInfo()) {
				return false;
			}
			return mailSenderService.convertAndSend(mail);
		} catch (Exception e) {
			logger.error("邮件发送失败：文本格式:{}", e.getMessage(), e);
		}
		return false;
	}

	@Override
	public boolean send(TextMail mail, String freemarkerTemplatePath, Pair<?, ?>... pairs) {
		if (mail.checkInfo()) {
			return false;
		}
		HashMap<Object, Object> hashMap = packageFreemarkerPairs(mail, pairs);
		mail.setText(generateContent(hashMap, MAIL_TEMPLATE_PATH + freemarkerTemplatePath));
		return send(mail);
	}

	@Override
	public boolean send(HtmlMail mail) {
		try {
			if (mail.checkInfo()) {
				return false;
			}
			return mailSenderService.convertAndSend(mail);
		} catch (Exception e) {
			logger.error("邮件发送失败：html格式:{}", e.getMessage(), e);
		}
		return false;
	}

	@Override
	public boolean send(HtmlMail mail, String freemarkerTemplatePath, Pair<?, ?>... pairs) {
		if (mail.checkInfo()) {
			return false;
		}
		HashMap<Object, Object> hashMap = packageFreemarkerPairs(mail, pairs);
		mail.setText(generateContent(hashMap, MAIL_TEMPLATE_PATH + freemarkerTemplatePath));
		return send(mail);
	}

	@Override
	public boolean send(FileMail mail) {
		try {
			if (mail.checkInfo()) {
				return false;
			}
			return mailSenderService.convertAndSend(mail);
		} catch (Exception e) {
			logger.error("邮件发送失败：附件格式:{}", e.getMessage(), e);
		}
		return false;
	}

	@Override
	public boolean send(FileMail mail, String freemarkerTemplatePath, Pair<?, ?>... pairs) {
		if (mail.checkInfo()) {
			return false;
		}
		HashMap<Object, Object> hashMap = packageFreemarkerPairs(mail, pairs);
		mail.setText(generateContent(hashMap, MAIL_TEMPLATE_PATH + freemarkerTemplatePath));
		return send(mail);
	}

	HashMap<Object, Object> packageFreemarkerPairs(BaseMail mail, Pair<?, ?>... pairs) {
		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
		hashMap.put("sign", "刘金磊");
		hashMap.put("signEmail", "liujinlei@pingdagroup.com");
		hashMap.put("subject", mail.getSubject());
		if (mail.getSourceSys() != null) {
			hashMap.put("fixSystemName", mail.getSourceSys().get_alias());
		}
		hashMap.put("context", mail.getText());
		hashMap.put("contextPairs", getContext(pairs));
		return hashMap;
	}

	public String getContext(Pair<?, ?>... context_list) {
		if (ArrayUtils.isNotEmpty(context_list)) {
			StringBuilder stringBuilder = new StringBuilder("<dl>");
			for (Pair<?, ?> pair : context_list) {
				stringBuilder.append("<dt>");
				stringBuilder.append(pair.getLeft());
				stringBuilder.append("</dt>");
				stringBuilder.append("<dd>");
				stringBuilder.append(pair.getRight());
				stringBuilder.append("</dd>");
			}
			stringBuilder.append("</dl>");
			return stringBuilder.toString();
		}
		return "";
	}

	/**
	 * 使用Freemarker生成html格式内容
	 * 
	 * @param replaceData 要替换的内容
	 * @param templatePath 模板路径
	 */
	protected String generateContent(Map<Object, Object> replaceData, String templatePath) {
		try {
			if (configuration == null) {
				configuration = freemarker.createConfiguration();
			}
			return FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(templatePath), replaceData);
		} catch (IOException e) {
			logger.error("生成邮件读取FreeMarker模板错误：{}-{}", templatePath, e.getMessage(), e);
			throw new NullPointerException("FreeMarker模板不存在" + templatePath);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败：{}-{}", templatePath, e.getMessage(), e);
			throw new NullPointerException("FreeMarker处理失败" + templatePath);
		}
	}
}